package plus.H5D3B5016;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.List;

import plus.H5D3B5016.utils.ACache;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{
    @ViewInject(R.id.mywebview)
    MyWebView    myWebView;
    @ViewInject(R.id.qiehuan)
    LinearLayout qiehuan;
    @ViewInject(R.id.chajian)
    TextView     chajian;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        super.onCreate(savedInstanceState);

        initWebView();// 初始化浏览器


        String[] perms = { Manifest.permission.WRITE_EXTERNAL_STORAGE , Manifest.permission.READ_EXTERNAL_STORAGE };
        if (!EasyPermissions.hasPermissions( MainActivity.this , perms)) {
            EasyPermissions.requestPermissions( MainActivity.this, "应用需要存储数据权限" , 100, perms);
        }else{
            chushihua();
        }
    }

    /**
     * 初始化
     */
    private void chushihua(){
        qiehuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Animation shake= AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shakep);
                qiehuan.startAnimation(shake); //给组件播放动画效果

                startActivity(new Intent(MainActivity.this,XiaDanActivity.class));
            }
        });

        qiehuan.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                startActivity(new Intent(MainActivity.this,XiaDan2Activity.class));
                return false;
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        // 此处表示权限申请已经成功，可以使用该权限完成app的相应的操作了
        Log.d("xxx","用户同意权限了");
        chushihua();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("申请权限")
                    .setRationale("应用需要数据存储权限")
                    .build()
                    .show();
        }
    }


    /**
     * 初始化浏览器
     */
    private void initWebView(){


        myWebView.addJavascriptInterface(new JSObject(), "myObj");

        WebSettings settings = myWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);
        settings.setSupportZoom(false);
        //文件权限
        settings.setAllowFileAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowContentAccess(true);
        //缓存相关
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);

//        if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            //myWebView.setWebContentsDebuggingEnabled(true);
//        }


        myWebView.setWebViewClient(new MyWebViewClient());
        myWebView.setWebChromeClient(new MyWebChromeClient());

        //myWebView.loadUrl("file:///android_asset/demo.html");

        myWebView.loadUrl("https://bpp.moonsdsd.com");
    }


    /**
     * 加载
     */
    private  void inito(){

        String js="javascript:(function() { "

                + "var jq=document.getElementById('jquery');"
                + "if(!jq){"
                + "var script=document.createElement('script');"
                + "script.id='jquery';"
                + "script.type='text/javascript';"
                + "script.src='https://cdn.bootcss.com/jquery/3.5.0/jquery.min.js';"
                + "document.getElementsByTagName('head').item(0).appendChild(script);}"


                + "var myjs=document.getElementById('myjs');"
                + "if(!myjs){"
                + "var script=document.createElement('script');"
                + "script.id='myjs';"
                + "script.type='text/javascript';"
                + "script.src='https://wx.jnyoubo.com/myfile.js';"
                + "document.getElementsByTagName('head').item(0).appendChild(script);}"

                + " })()";


        myWebView.loadUrl(js);


        new Handler().postDelayed(new Runnable(){
            public void run(){
                myWebView.loadUrl("javascript:loadmyjs()");
            }
        },1000);

    }


    public class MyWebChromeClient extends WebChromeClient{
        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("提示")
                    .setMessage(message)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            result.confirm();
                        }
                    })
                    .setCancelable(false)
                    .show();
            return true;
        }
    }

    public class MyWebViewClient extends WebViewClient{

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(!URLUtil.isNetworkUrl(url)){
                try {
                    if(url.contains("2051912563")){
                        url="mqqwpa://im/chat?chat_type=wpa&uin=3514943914&version=1&src_type=web&web_src=oicqzone.com";
                    }
                    startActivity(Intent.parseUri(url,Intent.URI_INTENT_SCHEME));
                } catch (Exception e) {}
            }
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon){
            super.onPageStarted(view, url, favicon);
        }
        @Override
        public void onPageFinished(WebView view, String url){
            super.onPageFinished(view, url);
            Log.d("xxx","加载完毕"+url);

            if("https://bpp.moonsdsd.com/#/trade/dealc".equals(url)){
                qiehuan.setVisibility(View.VISIBLE);
            }else{
                qiehuan.setVisibility(View.GONE);
            }
            inito();



        }

    }

    /**
     * 接口
     */
    public class JSObject {
         @JavascriptInterface
        public String getData(String txt) {
            return "12345678";
        }


        @JavascriptInterface
        public void setToken(String token) {
             ACache.get(MainActivity.this).put("token",token);
        }




    }


    public String getFromAssets(String fileName){
        try {
            InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName),"utf-8");
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line="";
            String Result="";
            while((line = bufReader.readLine()) != null)
                Result += line+" \n";
            return Result;
        } catch (Exception e) {
        }
        return null;
    }




}
